package topcbl.ai;

import java.util.HashMap;
import java.util.Vector;

import topcbl.room.Player;

public class DominoAI extends Player {

	Vector<HashMap<String, Integer>> blockSet = new Vector<HashMap<String, Integer>>();
	int mLeftNum = -1, mRightNum = -1;
	String mMessageFromServer = "";

	public DominoAI(String name) {
		super(name);
	}

	@Override
	public void sendMessage(String str) {
		String[] stream = str.split("_");
		String code = stream[0];
		String data = stream[1];
		switch (code) {
		case "TAKEBLOCK":
			String[] dataSplited = data.split(":");
			HashMap<String, Integer> map = new HashMap<String, Integer>();
			map.put("1st", Integer.parseInt(dataSplited[0]));
			map.put("2nd", Integer.parseInt(dataSplited[1]));
			blockSet.add(map);
			break;
		case "CAN":
			mMessageFromServer = str;
			break;
		case "CHECK":
			mMessageFromServer = str;
			break;
		case "PLAY":
			String[] splitData = data.split(":");
			String side = splitData[2];
			int num1 = Integer.parseInt(splitData[0]);
			int num2 = Integer.parseInt(splitData[1]);
			if (side.equals("left")) {
				mLeftNum = mLeftNum == num1 ? num2 : num1;
			} else {
				mRightNum = mRightNum == num1 ? num2 : num1;
			}
			break;
		case "FIRSTPLAY":
			String[] _splitData = data.split(":");
			int _num1 = Integer.parseInt(_splitData[0]);
			int _num2 = Integer.parseInt(_splitData[1]);
			mLeftNum = _num1 < _num2 ? _num1 : _num2;
			mRightNum = _num1 > _num2 ? _num1 : _num2;
			break;
		case "COUNT":
			mMessageFromServer = str;
			break;
		default:
		}
	}

	@Override
	public String receiveMessage() throws Exception {
		switch (mMessageFromServer) {
		case "CAN_PLAY":
			return playGame();
		case "CHECK_0":
			return "I'M_HERE";
		case "COUNT_POINT":
			int result = 0;
			for (int i = 0; i < blockSet.size(); i++) {
				result += blockSet.get(i).get("1st");
				result += blockSet.get(i).get("2nd");
			}
			return String.valueOf(result);
		default:
			return "";
		}
	}

	@Override
	public boolean isServer() {
		return false;
	}

	private String playGame() {
		if (blockSet.size() == 0) {
			return "LOSE_0";
		} else {
			for (int i = 0; i < blockSet.size(); i++) {
				int num1 = blockSet.get(i).get("1st");
				int num2 = blockSet.get(i).get("2nd");
				if (num1 == mLeftNum || num2 == mLeftNum) {
					mLeftNum = mLeftNum == num1 ? num2 : num1;
					blockSet.remove(i);
					return "PLAY_" + num1 + ":" + num2 + ":" + "left";
				} else if (num1 == mRightNum || num2 == mRightNum) {
					mRightNum = mRightNum == num1 ? num2 : num1;
					blockSet.remove(i);
					return "PLAY_" + num1 + ":" + num2 + ":" + "right";
				}
			}
		}
		return "DROP_TURN";
	}

}
